package com.ruoyi.contract.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.base.domain.SProjectFee;
import com.ruoyi.base.service.ISProjectFeeService;
import com.ruoyi.clp.domain.CCompany;
import com.ruoyi.clp.service.CCompanyService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.contract.annotation.enums.ConBusinessOperType;
import com.ruoyi.contract.constant.ConConstants;
import com.ruoyi.contract.domain.ConBusiness;
import com.ruoyi.contract.domain.ConBusinessType;
import com.ruoyi.contract.domain.ConObjOut;
import com.ruoyi.contract.domain.VCtmsClient;
import com.ruoyi.contract.domain.vo.ConBusinessDetail;
import com.ruoyi.contract.service.*;
import com.ruoyi.finance.collection.mapper.VBillCollectionMapper;
import com.ruoyi.finance.collection.service.VBillCollectionService;
import com.ruoyi.system.domain.web.SelectLabel;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 合同主Controller
 *
 * @author ruoyi
 * @date 2021-09-08
 */
@RestController
@RequestMapping("/business")
public class ConBusinessController extends BaseController {
    @Autowired
    private IConBusinessService conBusinessService;

    @Autowired
    VCtmsClientService vCtmsClientService;

    @Autowired
    IConObjOutService conObjOutService;

    @Autowired
    IConCusRelaService conCusRelaService;

    @Autowired
    ISysUserService iSysUserService;

    @Autowired
    IConOperLogService conOperLogService;

    @Autowired
    IConBusinessTypeService conBusinessTypeService;

    @Autowired
    ISProjectFeeService isProjectFeeService;

    @Autowired
    CCompanyService cCompanyService;
    
    @Autowired
    VBillCollectionService vBillCollectionService;


    /**
     *外部对象下拉
     */
    @GetMapping("/VCtmsClientLabel")
    public List<SelectLabel> VCtmsClientLabel(){
        QueryWrapper<VCtmsClient> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(VCtmsClient::getAbandonedMark,"0");
        List<VCtmsClient> cusData1 = vCtmsClientService.getlist(queryWrapper);
        List<SelectLabel> labels = new ArrayList<>();
        if(cusData1.size()>0){
            for(VCtmsClient cusdata:cusData1){
                SelectLabel label = new SelectLabel();
                label.setLabel(cusdata.getCnCustomerNam());
                label.setValue(cusdata.getCustomerGkey());
                labels.add(label);
            }
        }
        return  labels;
    }

    /**
     *码头下拉
     */
    @GetMapping("/getCompanyCode")
    public List<SelectLabel> getCompanyCode(){
        QueryWrapper<CCompany> queryWrapper = new QueryWrapper<>();
        List<CCompany> cCompanyList= cCompanyService.list(queryWrapper);
//        System.out.println("1111111111111111"+cCompanyList);
        List<SelectLabel> labels = new ArrayList<>();
        if(cCompanyList.size()>0){
            for(CCompany cusdata:cCompanyList){
                SelectLabel label = new SelectLabel();
                label.setLabel(cusdata.getCnCompanyNam());
                label.setValue(cusdata.getCompanyCod());
                labels.add(label);
            }
        }
        return  labels;
    }


//    /**
//     *业务类型下拉
//     */
//    @GetMapping("/SprojectLabel")
//    public List<SelectLabel> SprojectLabel(){
//        List<SProjectFee> cusData1 = isProjectFeeService.list();
//        List<SelectLabel> labels = new ArrayList<>();
//        if(cusData1.size()>0){
//            for(SProjectFee cusdata:cusData1){
//                SelectLabel label = new SelectLabel();
//                label.setLabel(cusdata.getProjectFeeName());
//                label.setValue(cusdata.getProjectFeeId());
//                labels.add(label);
//            }
//        }
//        return  labels;
//    }


    /**
     * 查询合同主列表
     */
    @GetMapping("/list")
    public TableDataInfo list(ConBusiness ConBusiness) {
        startPage();
        List<ConBusiness> list = conBusinessService.selectConBusinessList(ConBusiness);
        System.out.println("22222222"+list);
        return getDataTable(list);
    }
    /**
     * 获取合同主详细信息
     */
    @GetMapping(value = "/{conId}")
    public AjaxResult getInfo(@PathVariable("conId") Long conId) {
        ConBusiness conBusiness = conBusinessService.getById(conId);
        ConBusinessDetail conBusinessDetail = conBusinessService.selectConBusinessById(conId);
        List<String> conCusRelaListA = conObjOutService.getCusIdListByConIdAndTypes(conId);
        conBusinessDetail.setCustomerGkeys(conCusRelaListA);
        conBusinessDetail.setConBusTypes(conBusinessTypeService.getBusTypeByConId(conId));
        SysUser sysUser = iSysUserService.selectUserByUserName(conBusiness.getHandleName());
        conBusinessDetail.setHandleName(sysUser.getNickName());
        return AjaxResult.success(conBusinessDetail);
    }

    /**
     * 新增合同主
     */
    @PostMapping("/add")
    @Transactional
    @Log(title = "新增合同", businessType = BusinessType.INSERT)
    public AjaxResult add(@RequestBody ConBusinessDetail conBusinessDetail) {
        String con=conBusinessService.getConCode(conBusinessDetail.getConCode());
        if(con!=null&&con!=""){
            return AjaxResult.error("合同代码已存在");
        }
//        if(!(String.valueOf(conBusinessDetail.getConPriority()).matches("\\d+"))||conBusinessDetail.getConPriority()<0){
//            return AjaxResult.error("请输入整数");
//        }
        ConBusiness conBusiness = new ConBusiness(conBusinessDetail);
        // String conCode = serialService.getSerialNumberByCode(ConConstants.conSerialCode);
        conBusiness.setConCode(conBusinessDetail.getConCode());
        conBusiness.setHandleName(SecurityUtils.getUsername());
        conBusiness = ConBusiness.addinit(conBusiness);
//        SysUser sysUser = iSysUserService.getOne(new QueryWrapper<SysUser>().lambda().eq(SysUser::getUserName, SecurityUtils.getUsername()));
        conBusiness.setCompanyCode(conBusinessDetail.getCompanyCod());
        String  ccname=cCompanyService.getCnCompanyNam(String.valueOf(conBusinessDetail.getCompanyCod()));
        conBusiness.setCompanyNam(ccname);
        if (conBusinessService.save(conBusiness)) {
                for (String cusId : conBusinessDetail.getCustomerGkeys()) {
                    QueryWrapper<VCtmsClient> queryWrapper = new QueryWrapper<>();
                    queryWrapper.lambda().eq(VCtmsClient::getCustomerGkey,cusId).eq(VCtmsClient::getAbandonedMark,"0");
                    VCtmsClient vCtmsClient = vCtmsClientService.getVCtmsClientByCustomerGkey(queryWrapper);
                    conObjOutService.saveObjOut(vCtmsClient, conBusiness);
                }
            }
            /*生成合同业务类型*/
            for (String conBusType : conBusinessDetail.getConBusTypes()) {
                ConBusinessType conBusinessType = new ConBusinessType();
                conBusinessType.setConBussinessType(conBusType);
                conBusinessType.setConId(conBusiness.getConId());
                conBusinessTypeService.save(conBusinessType);
            }
        conBusinessDetail.setConCode(conBusiness.getConCode());
        conBusinessDetail.setConId(conBusiness.getConId());
        conBusinessDetail.setConPriority(conBusiness.getConPriority());

        /*操作记录*/
        conOperLogService.saveConOperLog(conBusiness.getConId(), ConBusinessOperType.INSERT.getName(), null);

        return AjaxResult.success(conBusinessDetail);
    }

    /**
     * 修改合同主
     */
    @Log(title = "修改合同", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody ConBusinessDetail conBusinessDetail) {
        ConBusiness conBusiness = conBusinessService.getById(conBusinessDetail.getConId());
        if (!conBusinessService.operateAble(conBusiness.getConId())) {
            return AjaxResult.error("已冻结或作废无法操作！");
        }
        StringBuffer editDetail = new StringBuffer();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        conBusiness.setConCode(conBusinessDetail.getConCode());
        conBusiness.setConStartTime(conBusinessDetail.getConStartTime());
        conBusiness.setConEndTime(conBusinessDetail.getConEndTime());
        conBusiness.setIsTemplate(conBusinessDetail.getIsTemplate());
        conBusiness.setRemark(conBusinessDetail.getRemark());
        conBusiness.setCompanyCode(conBusinessDetail.getCompanyCod());
        if (conBusinessDetail.getConPriority()==null){
            conBusiness.setConPriority(0);
        }else{
            conBusiness.setConPriority(conBusinessDetail.getConPriority());
        }
        String  ccname=cCompanyService.getCnCompanyNam(String.valueOf(conBusinessDetail.getCompanyCod()));
        conBusiness.setCompanyNam(ccname);
        SysUser sysUser = iSysUserService.selectUserByUserName(conBusiness.getHandleName());
//        if(conBusiness.getHandleName()==null&&conBusinessDetail.getHandleName()!=null){
//            conBusiness.setHandleName(conBusinessDetail.getHandleName());
//        }else if(!conBusinessDetail.getHandleName().toString().equals(sysUser.getNickName().toString())){
//            conBusiness.setHandleName(conBusinessDetail.getHandleName());
//        }
        // 更新外部对象
        conObjOutService.remove(new QueryWrapper<ConObjOut>().lambda().eq(ConObjOut::getConId,conBusiness.getConId()));
        for (String cusId : conBusinessDetail.getCustomerGkeys()) {
            QueryWrapper<VCtmsClient> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(VCtmsClient::getCustomerGkey,cusId).eq(VCtmsClient::getAbandonedMark,"0");
            VCtmsClient vCtmsClient = vCtmsClientService.getVCtmsClientByCustomerGkey(queryWrapper);
            conObjOutService.saveObjOut(vCtmsClient, conBusiness);
        }
        if (conBusinessService.updateById(conBusiness)) {
            conBusinessTypeService.remove(new QueryWrapper<ConBusinessType>().lambda().eq(ConBusinessType::getConId, conBusinessDetail.getConId()));
              /*生成合同业务类型*/
            for (String conBusType : conBusinessDetail.getConBusTypes()) {
                ConBusinessType conBusinessType = new ConBusinessType();
                conBusinessType.setConBussinessType(conBusType);
                conBusinessType.setConId(conBusiness.getConId());
                conBusinessTypeService.save(conBusinessType);
            }
            /*操作记录*/
            conOperLogService.saveConOperLog(conBusiness.getConId(), ConBusinessOperType.EDIT.getName(), editDetail.toString());
        }
        return AjaxResult.success();
    }

    /**
     * 删除合同
     */
    @PostMapping("/delete/{conId}")
    @Log(title = "删除合同", businessType = BusinessType.DELETE)
    public AjaxResult deleteContractById(@PathVariable("conId") Long conId) {
        ConBusiness conBusiness = conBusinessService.getById(conId);
        SysUser sysUser = iSysUserService.selectUserByUserName(SecurityUtils.getUsername());
        conBusiness.setDelName(sysUser.getUserName());
        conBusiness.setDelFlag("2");
        conBusiness.setDelTime(new Date());
        conOperLogService.saveConOperLog(conId, ConBusinessOperType.INVALID.getName(), null);
        return conBusinessService.removeById(conBusiness) == true ? AjaxResult.success() : AjaxResult.error("删除失败");
    }

    /**
     * 作废合同
     */
    @PostMapping("/nullify/{conId}")
    @Log(title = "作废合同", businessType = BusinessType.UPDATE)
    public AjaxResult nullifyContractById(@PathVariable("conId") Long conId) {
        ConBusiness conBusiness = conBusinessService.getById(conId);
        SysUser sysUser = iSysUserService.selectUserByUserName(SecurityUtils.getUsername());
        conBusiness.setDelName(sysUser.getUserName());
        conBusiness.setIsFrozen(ConConstants.invalid);
        conBusiness.setDelTime(new Date());
        conOperLogService.saveConOperLog(conId, ConBusinessOperType.INVALID.getName(), null);
        return conBusinessService.updateById(conBusiness) == true ? AjaxResult.success() : AjaxResult.error("作废失败");
    }

    /**
     * 恢复作废合同
     */
    @PostMapping("/restoreNullify/{conId}")
    @Log(title = "恢复作废合同", businessType = BusinessType.UPDATE)
    public AjaxResult restoreNullify(@PathVariable("conId") Long conId) {
        ConBusiness conBusiness = conBusinessService.getById(conId);
        conBusiness.setIsFrozen("0");
        conOperLogService.saveConOperLog(conId, "恢复作废合同", null);
        return conBusinessService.updateById(conBusiness) == true ? AjaxResult.success() : AjaxResult.error("恢复失败");
    }

    /**
     * 根据传入的合同id，复制合同
     * @param conId 需要复制的合同id
     * @return 结果
     */
    @PostMapping("/copyContractById/{conId}")
    @Log(title = "复制合同", businessType = BusinessType.INSERT)
    public AjaxResult copyContractById(@PathVariable("conId") Long conId) {
        if (conId == null) {
            return AjaxResult.error("传入的合同id为空，请检查！");
        }
        
        Long newConId = conBusinessService.copyContractById(conId);
        if (newConId != null) {
            conOperLogService.saveConOperLog(conId, "复制合同", String.format("复制成功，原合同id：%s", conId));
            return AjaxResult.success(String.format("复制合同成功，新合同id：【%s】！", newConId));
        } else {
            conOperLogService.saveConOperLog(conId, "复制合同", String.format("复制失败，原合同id：%s", conId));
            return AjaxResult.error("复制合同失败！");
        }
        
    }
    
    /**
     * 根据projectId 获取合同列表
     *
     * @param projectId
     * @return
     */
    @GetMapping("/listContractByProjectId")
    public AjaxResult listContractByProjectId(Long projectId) {
        return AjaxResult.success(conBusinessService.listContractByProjectId(projectId));
    }

    /**
     * 根据statementId查询该对账单下费项所绑定计费合同的conId
     * @param statementId
     * @return
     */
    @PostMapping("/getConIdByStatementId")
    public AjaxResult getConIdByStatementId(@RequestBody Long statementId) {
        return AjaxResult.success((vBillCollectionService.getConIdByStatementId(statementId)));
    }
    
    
    
}
